<?php


/**
 * UserController
 *-------------------------
 *
 * Deal with user profile, task, feedback 
 *
 * PHP versions 5
 *
 * LICENSE: This source file is from Smarter Ver4.0, which is a comprehensive shopping engine
 * that helps consumers to make smarter buying decisions online. We empower consumers to compare
 * the attributes of over one million products in the computer and consumer electronics categories
 * and to read user product reviews in order to make informed purchase decisions. Consumers can then
 * research the latest promotional and pricing information on products listed at a wide selection of
 * online merchants, and read user reviews on those merchants.
 * The copyrights is reserved by http://www.mezimedia.com.
 * Copyright (c) 2005, Mezimedia. All rights reserved.
 *
 * @author     kevin cheng <kevin_cheng@mezimedia.com>
 * @copyright  (C) 2004-2008 Mezimedia.com
 * @license    http://www.mezimedia.com  PHP License 5.2
 * @version    CVS: $Id: UserController.php
 * @link       http://pms.mezimedia.com/
 * @deprecated File deprecated in Release 1.0
 */

require_once 'app/lib/Pager.php';

class UserController extends Zend_Controller_Action {
	/*
	 * @Desc: Set the controller sub-menu, before action execute. 
	 * @params: null
	 * @output: init the page view and submenu
	 */
	function preDispatch() {
		$curruser = Zend_Auth::getInstance()->getIdentity();
		$this->view->user = $curruser['userName'];
		$this->view->controller = $this->_request->getControllerName();
		$this->view->action = $this->_request->getActionName();
		$subMenu = array (
			'Main' => array (
				'key' => 'index',
				'url' => '/user/',
				'selected' => false,
				'title' => 'Page to list user todo, msg ...',
			),
			'My Tasks' => array (
				'key' => 'tasks',
				'url' => '/user/tasks',
				'selected' => false,
				'title' => 'Tasks assigned to me'
			),
			'Profile' => array (
				'key' => 'profile',
				'url' => '/user/profile',
				'selected' => false,
				'title' => 'Basic info, change password'
			),
			'Messages' => array (
				'key' => 'messages',
				'url' => '/user/messages',
				'selected' => false,
				'title' => 'Messages received by me'
			)
		);
		$menu = new Menu();
		$menuTree = $menu->renderMenu($this->_request->getControllerName(), $this->_request->getActionName(), $subMenu);
		/*echo $this->_request->getControllerName()." -> ".$this->_request->getActionName();
		exit;*/
		$this->view->menuTree = $menuTree;
		$this->tns = new Zend_Session_Namespace('TT_User');

		
		$this->view->metaTitle = "User - Task Tracking System V1.0";
	}

	function indexAction() {	
		$authNamespace = Zend_Auth::getInstance()->getIdentity();
		//get unread message count
		Zend_Loader :: loadClass('Message');		
		$oMessage = new Message();
		$unreadMsgCount = $oMessage->getUnreadMsgCount($authNamespace['userId']);		
		$this->view->unreadMsgCount = $unreadMsgCount;
		
		//get new task count
		Zend_Loader :: loadClass('Task');
		$oTask = new Task();
		$this->view->taskCounts = $oTask->getTaskCounts($authNamespace['userId']);		
	}
	
	/*Task list for current user*/
	function tasksAction(){
		$authNamespace = Zend_Auth::getInstance()->getIdentity();
		$DB = Zend_Registry :: get('db_adapter');
		$sql = "SELECT count(*) FROM tt_st_task WHERE (developer_id =".$authNamespace['userId']." OR manager_id=".$authNamespace['userId']." OR request_id=".$authNamespace['userId'].") ";
		if($this->_getParam('type') == 'finished') {	
			$this->view->listType = 'finished';
			$sql .= "AND task_status = ".__TASK_FINISHED;
		}else{
			$this->view->listType = '';
			$sql .= "AND task_status <> ".__TASK_FINISHED;		
		}		
		$taskCount = $DB->fetchOne($sql);				
		$this->view->taskCount = $taskCount;
		
		//initial the paging
		$this->view->base_url = '/user/tasks/';
		$this->view->this_url = $_SERVER['REQUEST_URI'];
		$this->view->page_url = ($this->tns->now_page > 1) ? $this->view->base_url.'index/p/'.$this->tns->now_page : $this->view->base_url;		
		$params = array('item'=>5, 'p'=>$this->_getParam('p'));
		$pagingUrl = $this->view->base_url;
		if($this->_getParam('type') == 'finished'){
			$pagingUrl .= 'type/'.$params['type'].'/';
		}
		$pagingUrl .= 'p/{page}';
		$pat = array('Mode' => 2, 'Paging' => $pagingUrl, 'Prev' => '<', 'Next' => '>');
		$obj = new Pager($params['item'], $params['p'], $taskCount, $pat);
		$pager = $obj->toArray();
		
		$authNamespace = Zend_Auth::getInstance()->getIdentity();
		$DB = Zend_Registry :: get('db_adapter');
		$sql = "SELECT id, title, date_start, duration, task_status from tt_st_task WHERE (developer_id =".$authNamespace['userId']." OR manager_id=".$authNamespace['userId']." OR request_id=".$authNamespace['userId'].")";
		if($this->_getParam('type') == 'finished') {	
			$sql .= "AND task_status = ".__TASK_FINISHED;
		}else{
			$sql .= "AND task_status <> ".__TASK_FINISHED;		
		}		
		$sql .= " limit ".$pager['frNum'].",".$pager['itemNum'];
				
		$taskListRs = $DB->query($sql);
		
		$this->view->pager = ($pager['totalPage'] > 1) ? $pager : null;
		$this->view->taskList = $taskListRs->fetchAll();
		
	}

	function profileAction() {		
		$authNamespace = Zend_Auth::getInstance()->getIdentity();
		$DB = Zend_Registry :: get('db_adapter');
		//todo sql injection protect
		if($this->_getParam('act') == 'info') {
			try{
				$DB->query("UPDATE tt_user set email=?, phone=? where id =?", array (trim($_POST['email']), trim($_POST['phone']), $authNamespace['userId']));			
				//echo the success via the errors
				$this->view->displayErrorTitle = false;
				$this->view->errors = array('Profile has been changed!');			
			}catch(EXCEPTION $e){
				$this->view->errors = array($e->getMessage());	
			}			
		}else if($this->_getParam('act') == 'pwd'){
			$pwdrs = $DB->query('select email, phone from tt_user where id =? and passwd=?', array ($authNamespace['userId'], $_POST['currentPassword']));
			if ($pwdrs) {
				$userInfo= $pwdrs->fetchAll();
				if(count($userInfo) >0){
					$DB->query("UPDATE tt_user set passwd='".trim($_POST['newPassword'])."' where id =? and passwd=?", array ($authNamespace['userId'], $_POST['currentPassword']));
					$this->view->displayErrorTitle = false;
					$this->view->errors = array_merge(array('Your password has been changed!'));		
				}else{
					$this->view->errors = array_merge(array('Failed to updated your password, Please confirm your current password!'));
				}
			}
		}
		//fetch the info from db				
		$rs = $DB->query('select email, phone from tt_user where id =?', array ($authNamespace['userId']));		
		if ($rs) {
			$userInfo= $rs->fetchAll();
			$this->view->userInfo = $userInfo[0];									
		}

	}

	function messagesAction()
	{
		/*
		$MessageID		//Message's ID
		$oMessage		//message class
		$page_item		//each page item number
		*/

		$authNamespace = Zend_Auth::getInstance()->getIdentity();
		Zend_Loader :: loadClass('Zend_Db');
		Zend_Loader :: loadClass('Message');
		$DB = Zend_Db :: factory('Pdo_Mysql', Zend_Registry :: get('db_params_default'));
		$oMessage = new Message();
		
		$listType='r';
		if($this->_getParam('type') !='s'){
			$listType='r';	
		}
		$this->view->listType = $listType;

		// Page useful url
		$this->view->base_url = '/user/messages/';
		$this->view->this_url = $_SERVER['REQUEST_URI'];
		$this->view->page_url = ($this->tns->now_page > 1) ? $this->view->base_url.'index/p/'.$this->tns->now_page : $this->view->base_url;		
		$params = array('item'=>5, 'p'=>$this->_getParam('p'),'type'=>$listType);
		$pat = array('Mode' => 2, 'Paging' => $this->view->base_url.'type/'.$params['type'].'/p/{page}', 'Prev' => '<', 'Next' => '>');
		$obj = new Pager($params['item'], $params['p'], $oMessage->getTotal(), $pat);
		$pager = $obj->toArray();		
		$this->view->pager = ($pager['totalPage'] > 1) ? $pager : null;

		//del
		if($this->_getParam('hidaction') == 'del')
		{
			try
			{	
				$MessageID = $this->_getParam('hidid');
				$oMessage->deleMessage($MessageID);
			}
			catch (Exception $e)
			{
				print_r( array($e->getMessage()));
			}
			$this->_redirect($this->view->page_url);
		}
		
		//fetch the info from db
		if(!is_null($pager))
		{	
			$msgParams = array('userId'=>$authNamespace['userId'],'frNum'=>$pager['frNum'],'itemNum'=>$pager['itemNum'],'listType'=>$listType);
			
			$result = $oMessage->getMessagesList($msgParams);
			if(count($result) > 0)
			{
				$this->view->messagesList = $result;
			}
			$this->view->MessageCount = count($result);
		}
		else
		{
			$this->view->MessageCount = 0;
		}
	}

}